package com.example.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.juyixia.R;
import com.exanple.data.Activeinfo;

import android.app.Dialog;
import android.app.Service;
import android.R.integer;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.content.DialogInterface.OnClickListener;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.WindowManager;
import android.widget.Toast;
/**
 * 监听活动回复的服务
 * @author Administrator
 *
 */
public class ActiveService extends Service {
   private boolean isRun;
	public static final String bm = "utf-8";
	private Handler handler1; // 显示当前时间线程消息处理器。
	private Handler handler2; 
    private JSONObject recjson;
    private int num;//参与人数
    private int currentnum;//当前人数
    private double alllongitude;
    private double alllatitude;
    private double avealllongitude;
    private double avealllatitude;
    private String activeCreaterLoca;
    private  String ips[];
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}
	 public  boolean isHostConnectable(String host, int port) {
			Socket socket = new Socket();
			try {
				socket.connect(new InetSocketAddress(host, port));
				PrintWriter out = new PrintWriter(
						new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), bm)), true);
				out.println(recjson.toString());			
				out.close();
				
				// 关闭Socket
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			} finally {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return true;
			
		}
   @Override
public int onStartCommand(Intent intent, int flags, int startId) {
	// TODO Auto-generated method stub
	   
	   num=Integer.parseInt(intent.getStringExtra("人数"));
	   switch(Integer.parseInt(intent.getStringExtra("id"))){
		case 1:activeCreaterLoca="29.494749,106.576843";
		break;
		case 2:activeCreaterLoca="29.495300,106.581111";
		break;
		case 3:activeCreaterLoca="29.493586,106.581191";
		break;
		case 4:activeCreaterLoca="29.496447,106.578065";
		break;
		}
	   currentnum=0;
	   isRun=true;
	   alllatitude=0;//重置纬度
	   alllongitude=0;//重置经度
	   new Thread(new Runnable() {
		   
			@Override
			public void run() {
				// 定义一个线程中止标志

				try {

					ServerSocket serverSocket = new ServerSocket(22222);
					while (isRun) {
						Socket client = serverSocket.accept();
						currentnum++;
						BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), bm));
						String str = in.readLine();
						 recjson=new JSONObject(str);
                        if(currentnum<=num){
                        	alllatitude+=Double.parseDouble(recjson.getString("坐标").split(",")[0]);
                        	alllongitude+=Double.parseDouble(recjson.getString("坐标").split(",")[1]);
                        }
                        if(currentnum==num){                
                        	alllongitude+=Double.parseDouble(activeCreaterLoca.split(",")[1]);
                        	alllatitude+=Double.parseDouble(activeCreaterLoca.split(",")[0]);
                        	avealllongitude=alllongitude/(num+1);
                        	avealllatitude=alllatitude/(num+1);
                        	Message msg = new Message();
    						handler2.sendMessage(msg);
    						Activeinfo.activelist.add(new Activeinfo(recjson.getString("活动名"), recjson.getString("参与者"), "2017.6.9"));
    						ips=recjson.getString("allip").split(",");
    						new Thread() {
    						public void run() {				
    							try {
    								
    								for (String ip : ips) {
    									//if(isHostConnectable(ip, 54321)){
    									//	continue;
    									//}
    									Socket socket = null;
    									try {
    										// 创建Socket
    										// socket = new Socket("192.168.1.110",54321);
    										socket = new Socket(ip, 47777); 
    										
    										// 向服务器发送消息
    										PrintWriter out = new PrintWriter(
    												new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),bm)), true);
    										out.println(recjson.toString());
    										
    										out.close();
    										
    										// 关闭Socket
    										socket.close();
    									} catch (Exception e) {
    										// TODO: handle exception
    										
    									}
    								}
    								
    								
    							} catch (Exception e) {
    								// TODO: handle exception
    								
    							}
    		
    						}
    		
    			
    						
    					}.start();
                        }
						Message msg = new Message();
						handler1.sendMessage(msg);
						
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} 
			}
		}).start();
	   handler1 = new Handler(new Handler.Callback() {// 这样写，就不弹出什么泄漏的警告了
			@Override
			public boolean handleMessage(Message msg) {
				try {
					Toast.makeText(getApplicationContext(), recjson.getString("用户名")+"同意参与，"+ips.length+"坐标为："+recjson.getString("坐标"),
						     Toast.LENGTH_SHORT).show();
				} catch (NotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return false;
			}
		});
	   handler2 = new Handler(new Handler.Callback() {// 这样写，就不弹出什么泄漏的警告了
			@Override
			public boolean handleMessage(Message msg) {
				try {
					Toast.makeText(getApplicationContext(),"平均坐标为："+avealllatitude+","+avealllongitude,
						     Toast.LENGTH_SHORT).show();
				} catch (NotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return false;
			}
		});
	   return START_STICKY;
}
   @Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		isRun=false;
	}
}
